﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI.WebControls;

namespace Common
{
    /// <summary>
    /// 页面数据校验
    /// Copyright (C)
    /// </summary>
    public class PageValidate
    {
        private static Regex RegPhone = new Regex("^[0-9]+[-]?[0-9]+[-]?[0-9]$");
        private static Regex RegNumber = new Regex("^[0-9]+$");
        private static Regex RegNumberSign = new Regex("^[+-]?[0-9]+$");
        private static Regex RegDecimal = new Regex("^[0-9]+[.]?[0-9]+$");
        private static Regex RegDecimalSign = new Regex("^[+-]?[0-9]+[.]?[0-9]+$"); //等价于^[+-]?\d+[.]?\d+$
        private static Regex RegEmail = new Regex("^[\\w-]+@[\\w-]+\\.(com|net|org|edu|mil|tv|biz|info)$");//w 英文字母或数字的字符串，和 [a-zA-Z0-9] 语法一样 
        private static Regex RegCHZN = new Regex("[\u4e00-\u9fa5]");

        #region 电话号码检查
        /// <summary>
        /// 电话号码检查
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns></returns>
        public static bool IsPhone(string inputData)
        {
            Match m = RegPhone.Match(inputData);
            return m.Success;
        }
        #endregion

        #region 检查Request查询字符串的键值，是否是数字，最大长度限制
        /// <summary>
        /// 检查Request查询字符串的键值，是否是数字，最大长度限制
        /// </summary>
        /// <param name="req">Request</param>
        /// <param name="inputKey">Request的键值</param>
        /// <param name="maxLen">最大长度</param>
        /// <returns>返回Request查询字符串</returns>
        public static string FetchInputDigit(HttpRequest req, string inputKey, int maxLen)
        {
            string retVal = string.Empty;
            if (inputKey != null && inputKey != string.Empty)
            {
                retVal = req.QueryString[inputKey];
                if (null == retVal)
                    retVal = req.Form[inputKey];
                if (null != retVal)
                {
                    retVal = SqlText(retVal, maxLen);
                    if (!IsNumber(retVal))
                        retVal = string.Empty;
                }
            }
            if (retVal == null)
                retVal = string.Empty;
            return retVal;
        }
        #endregion

        #region 是否数字字符串
        /// <summary>
        /// 是否数字字符串
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns></returns>
        public static bool IsNumber<T>(T inputData)
        {
            Match m = RegNumber.Match(ConvertToTrimString(inputData));
            return m.Success;
        }
        #endregion

        #region 转换成字符串
        /// <summary>
        /// 转换成字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string ConvertToTrimString<T>(T source)
        {
            string result = string.Empty;

            if (source == null)
                result = "";
            else
                result = source.ToString();

            if (!String.IsNullOrEmpty(result))
            {
                result = result.Trim();
            }
            return result;
        }
        #endregion

        #region 转换成数字
        /// <summary>
        /// 转换成数字
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sParam"></param>
        /// <returns></returns>
        public static int ConvertToTrimInt<T>(T source)
        {
            int result;

            string sValue = ConvertToTrimString(source);

            int.TryParse(sValue, out result);

            return result;
        }
        #endregion

        #region 转换成decimal数字
        /// <summary>
        /// 转换成decimal数字
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sParam"></param>
        /// <returns></returns>
        public static decimal ConvertToTrimDecimal<T>(T source)
        {
            decimal result;

            string sValue = ConvertToTrimString(source);

            decimal.TryParse(sValue, out result);

            return result;
        }
        #endregion

        #region 转换成时间
        /// <summary>
        /// 转换成时间
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <returns></returns>
        public static DateTime ConvertToDateTime<T>(T source)
        {
            DateTime result = new DateTime();
            if (source == null)
                result = DateTime.Now;
            else
            {

                string time = PageValidate.ConvertToTrimString(source);
                if (DateTime.TryParse(time, out result))
                {
                    result = Convert.ToDateTime(source);
                }
                else
                {
                    result = DateTime.MinValue;
                }

            }
            return result;
        }
        #endregion

        #region 转换成布尔型(1为T，0为F)
        /// <summary>
        /// 转换成布尔型(1为T，0为F)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <returns></returns>
        public static bool ConvertToTrimBool<T>(T source)
        {
            if (ConvertToTrimInt(source) == 1)
            {
                return true;
            }
            return false;
        }
        #endregion

        #region 是否数字字符串 可带正负号
        /// <summary>
        /// 是否数字字符串 可带正负号
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns></returns>
        public static bool IsNumberSign(string inputData)
        {
            Match m = RegNumberSign.Match(inputData);
            return m.Success;
        }
        #endregion

        #region 是否是浮点数
        /// <summary>
        /// 是否是浮点数
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns></returns>
        public static bool IsDecimal(string inputData)
        {
            Match m = RegDecimal.Match(inputData);
            return m.Success;
        }
        #endregion

        #region 是否是浮点数 可带正负号
        /// <summary>
        /// 是否是浮点数 可带正负号
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns></returns>
        public static bool IsDecimalSign(string inputData)
        {
            Match m = RegDecimalSign.Match(inputData);
            return m.Success;
        }
        #endregion

        #region 检测是否有中文字符
        /// <summary>
        /// 检测是否有中文字符
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns></returns>
        public static bool IsHasCHZN(string inputData)
        {
            Match m = RegCHZN.Match(inputData);
            return m.Success;
        }

        #endregion

        #region 邮件地址
        /// <summary>
        /// 邮件地址
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns></returns>
        public static bool IsEmail(string inputData)
        {
            Match m = RegEmail.Match(inputData);
            return m.Success;
        }
        #endregion

        #region 日期格式判断
        /// <summary>
        /// 日期格式判断
        /// </summary>
        /// <param name="str">输入字符串</param>
        /// <returns></returns>
        public static bool IsDateTime(string str)
        {
            try
            {
                if (!string.IsNullOrEmpty(str) && str != "0001/1/1 0:00:00")
                {
                    DateTime.Parse(str);
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }
        #endregion

        #region 日期格式判断 反回日期
        /// <summary>
        /// 日期格式判断 反回日期
        /// </summary>
        /// <param name="str">输入字符串</param>
        /// <returns></returns>
        public static string IsDateTimeReturnTime(string str)
        {
            try
            {
                if (!string.IsNullOrEmpty(str))
                {
                    return DateTime.Parse(str).ToString();
                }
                else
                {
                    //return DateTime.Now;
                    //return Convert.ToDateTime(DateTime.Now);
                    return null;
                }
            }
            catch
            {
                return null;
            }
        }
        #endregion

        #region 检查字符串最大长度，返回指定长度的串
        /// <summary>
        /// 检查字符串最大长度，返回指定长度的串
        /// </summary>
        /// <param name="sqlInput">输入字符串</param>
        /// <param name="maxLength">最大长度</param>
        /// <returns></returns>			
        public static string SqlText(string sqlInput, int maxLength)
        {
            if (sqlInput != null && sqlInput != string.Empty)
            {
                sqlInput = sqlInput.Trim();
                if (sqlInput.Length > maxLength)//按最大长度截取字符串
                    sqlInput = sqlInput.Substring(0, maxLength);
            }
            return sqlInput;
        }
        #endregion

        #region 字符串编码
        /// <summary>
        /// 字符串编码
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns></returns>
        public static string HtmlEncode(string inputData)
        {
            return HttpUtility.HtmlEncode(inputData);
        }
        #endregion

        #region 设置Label显示Encode的字符串
        /// <summary>
        /// 设置Label显示Encode的字符串
        /// </summary>
        /// <param name="lbl">Label控件名</param>
        /// <param name="txtInput">输入字符串</param>
        public static void SetLabel(Label lbl, string txtInput)
        {
            lbl.Text = HtmlEncode(txtInput);
        }
        #endregion

        #region 设置Label显示Encode的字符串
        /// <summary>
        /// 设置Label显示Encode的字符串
        /// </summary>
        /// <param name="lbl">Label控件名</param>
        /// <param name="inputObj">输入字符串</param>
        public static void SetLabel(Label lbl, object inputObj)
        {
            SetLabel(lbl, inputObj.ToString());
        }
        #endregion

        #region 字符串清理
        /// <summary>
        /// 字符串清理
        /// </summary>
        /// <param name="inputString">输入字符串</param>
        /// <param name="maxLength">最大值</param>
        /// <returns></returns>
        public static string InputText(string inputString, int maxLength)
        {
            StringBuilder retVal = new StringBuilder();

            // 检查是否为空
            if ((inputString != null) && (inputString != String.Empty))
            {
                inputString = inputString.Trim();

                //检查长度
                if (inputString.Length > maxLength)
                    inputString = inputString.Substring(0, maxLength);

                //替换危险字符
                for (int i = 0; i < inputString.Length; i++)
                {
                    switch (inputString[i])
                    {
                        case '"':
                            retVal.Append("&quot;");
                            break;
                        case '<':
                            retVal.Append("&lt;");
                            break;
                        case '>':
                            retVal.Append("&gt;");
                            break;
                        default:
                            retVal.Append(inputString[i]);
                            break;
                    }
                }
                retVal.Replace("'", " ");// 替换单引号
            }
            return retVal.ToString();

        }
        #endregion

        #region 转换成 HTML code
        /// <summary>
        /// 转换成 HTML code
        /// </summary>
        /// <param name="str">输入字符串</param>
        /// <returns></returns>
        public static string Encode(string str)
        {
            str = str.Replace("&", "&amp;");
            str = str.Replace("'", "''");
            str = str.Replace("\"", "&quot;");
            str = str.Replace(" ", "&nbsp;");
            str = str.Replace("<", "&lt;");
            str = str.Replace(">", "&gt;");
            str = str.Replace("\n", "<br>");
            return str;
        }
        #endregion

        #region 解析html成 普通文本
        /// <summary>
        /// 解析html成 普通文本
        /// </summary>
        /// <param name="str">输入字符串</param>
        /// <returns></returns>
        public static string Decode(string str)
        {
            str = str.Replace("<br>", "\n");
            str = str.Replace("&gt;", ">");
            str = str.Replace("&lt;", "<");
            str = str.Replace("&nbsp;", " ");
            str = str.Replace("&quot;", "\"");
            return str;
        }
        #endregion

        #region 去除SQL字符串符号值
        /// <summary>
        /// 去除SQL字符串符号值
        /// </summary>
        /// <param name="sqlText">Sql字符串</param>
        /// <returns></returns>
        public static string SqlTextClear(string sqlText)
        {
            if (sqlText == null)
            {
                return null;
            }
            if (sqlText == "")
            {
                return "";
            }
            sqlText = sqlText.Replace(",", "");//去除,
            sqlText = sqlText.Replace("<", "");//去除<
            sqlText = sqlText.Replace(">", "");//去除>
            sqlText = sqlText.Replace("--", "");//去除--
            sqlText = sqlText.Replace("'", "");//去除'
            sqlText = sqlText.Replace("\"", "");//去除"
            sqlText = sqlText.Replace("=", "");//去除=
            sqlText = sqlText.Replace("%", "");//去除%
            sqlText = sqlText.Replace(" ", "");//去除空格
            return sqlText;
        }
        #endregion

        #region 是否由特定字符组成
        /// <summary>
        /// 是否由特定字符组成
        /// </summary>
        /// <param name="strInput">输入字符串</param>
        /// <returns></returns>
        public static bool isContainSameChar(string strInput)
        {
            string charInput = string.Empty;
            if (!string.IsNullOrEmpty(strInput))
            {
                charInput = strInput.Substring(0, 1);
            }
            return isContainSameChar(strInput, charInput, strInput.Length);
        }
        public static bool isContainSameChar(string strInput, string charInput, int lenInput)
        {
            if (string.IsNullOrEmpty(charInput))
            {
                return false;
            }
            else
            {
                Regex RegNumber = new Regex(string.Format("^([{0}])+$", charInput));
                //Regex RegNumber = new Regex(string.Format("^([{0}]{{1}})+$", charInput,lenInput));
                Match m = RegNumber.Match(strInput);
                return m.Success;
            }
        }
        #endregion

        #region 检查输入的参数是不是某些定义好的特殊字符：这个方法目前用于密码输入的安全检查
        /// <summary>
        /// 检查输入的参数是不是某些定义好的特殊字符：这个方法目前用于密码输入的安全检查
        /// </summary>
        public static bool isContainSpecChar(string strInput)
        {
            string[] list = new string[] { "123456", "654321" };
            bool result = new bool();
            for (int i = 0; i < list.Length; i++)
            {
                if (strInput == list[i])
                {
                    result = true;
                    break;
                }
            }
            return result;
        }
        #endregion

        #region 截取字符串
        /// <summary>
        /// 截取字符串
        /// </summary>
        /// <param name="sInString">原字符串</param>
        /// <param name="iCutLength">截取长度</param>
        /// <returns></returns>
        public static string SubString(string sInString, int iCutLength)
        {
            if (sInString == null || sInString.Length == 0 || iCutLength <= 0) return "";
            int iCount = System.Text.Encoding.GetEncoding(0).GetByteCount(sInString);
            if (iCount > iCutLength)
            {
                int iLength = 0;
                for (int i = 0; i < sInString.Length; i++)
                {
                    int iCharLength = System.Text.Encoding.GetEncoding(0).GetByteCount(new char[] { sInString[i] });
                    iLength += iCharLength;
                    if (iLength == iCutLength)
                    {
                        sInString = sInString.Substring(0, i + 1);
                        break;
                    }
                    else if (iLength > iCutLength)
                    {
                        sInString = sInString.Substring(0, i);
                        break;
                    }
                }
                //sInString = sInString + "...";
            }

            return sInString;
        }
        #endregion

        #region 获取IP地址
        /// <summary>
        /// 通过判断是否使用代理获取用户的真实IP地址
        /// </summary>
        /// <returns></returns>
        public static string GetIp()
        {
            string result = String.Empty;

            result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (result != null && result != String.Empty)
            {
                //可能有代理 //没有“.”肯定是非IPv4格式 
                if (result.IndexOf(".") == -1)
                    result = null;
                else
                {
                    if (result.IndexOf(",") != -1)
                    {
                        //有“,”，估计多个代理。取第一个不是内网的IP。 
                        result = result.Replace(" ", "").Replace("'", "");
                        string[] temparyip = result.Split(",;".ToCharArray());
                        for (int i = 0; i < temparyip.Length; i++)
                        {
                            if (IsIPAddress(temparyip[i])
                                && temparyip[i].Substring(0, 3) != "10."
                                && temparyip[i].Substring(0, 7) != "192.168"
                                && temparyip[i].Substring(0, 7) != "172.16.")
                            {
                                //找到不是内网的地址 
                                return temparyip[i];
                            }
                        }
                    }
                    else if (IsIPAddress(result))
                        //代理即是IP格式
                        return result;
                    else
                        //代理中的内容 非IP，取IP 
                        result = null;
                }

            }

            string IpAddress = (
                HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null &&
                HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != String.Empty
            ) ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

            if (null == result || result == String.Empty)
                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

            if (result == null || result == String.Empty)
                result = HttpContext.Current.Request.UserHostAddress;

            return result;
        }

        /// <summary>
        /// 通过正则判断字符串是否为IP地址
        /// </summary>
        /// <param name="str1"></param>
        /// <returns></returns>
        private static bool IsIPAddress(string str1)
        {
            if (str1 == null || str1 == string.Empty || str1.Length < 7 || str1.Length > 15) return false;

            string regformat = @"^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$";

            Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);
            return regex.IsMatch(str1);
        }
        #endregion

        #region 获取访问方式，True为电脑,False为手机
        /// <summary>
        /// 获取访问方式，True为电脑,False为手机
        /// </summary>
        /// <returns></returns>
        public static bool GetPcOrMobile(string uAgent)
        {
            string osPat = "mozilla|m3gate|winwap|openwave|Windows NT|Windows 3.1|95|Blackcomb|98|ME|X Window|Longhorn|ubuntu|AIX|Linux|AmigaOS|BEOS|HP-UX|OpenBSD|FreeBSD|NetBSD|OS/2|OSF1|SUN";
            //string uAgent = Request.ServerVariables["HTTP_USER_AGENT"];
            Regex reg = new Regex(osPat);
            if (reg.IsMatch(uAgent))
            {
                return true;
            }

            return false;
        }
        #endregion
    }
}
